import { Component, ViewChild, OnInit } from '@angular/core';
import { Http } from '@angular/http';
//Base components
import { RiskBaseComponent } from '../shared/components/riskBase.component';
import { CompaniesListComponent } from './companyList/companyList.component';
import { PaginationComponent } from '../shared/components/pagination/pagination.component';
//Models
import { AuthModel } from '../models/auth.model';
import { environment } from '../../environments/environment';
import { GoogleAnalyticsBeacon } from '../models/googleAnalytics.beacon'
//Services
import { ListingRiskService } from './listingRisk.service';
import { UtilsService } from '../shared/services/utils.service';
import { AnalyticsService } from '../shared/services/analytics.service'
import { NgxSmartModalService } from 'ngx-smart-modal';


@Component({
  selector: 'app-root',
  templateUrl: './listingRisk.component.html',
  styleUrls: ['./listingRisk.component.css'],
  providers: [ListingRiskService,]
})
export class ListingRiskComponent extends RiskBaseComponent implements OnInit {
  public riskClusters: any[];
  public riskDistribution: any[];
  public containerUrl: string = this.gaService.containerUrl;
  public readonly resourcesUrl: string = environment.resourcesUrl;

  @ViewChild('list') companyList: CompaniesListComponent;

  constructor(
    public ngxSmartModalService: NgxSmartModalService,
    private riskService: ListingRiskService,
    private analyticsService: AnalyticsService,
    private http: Http) {
    super(http);
  }

  ngOnInit() {
    this.gaService.showPreloader();
    this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESG RR Landing Page', 'ESG Risk Rating'));

    this.getCompanyClusters().then(clusters => {
      this.riskClusters = clusters;
      this.riskService.getCompaniesBenchmark().then(data => {
        var result: any[] = []

        let maxLimit: number = Math.min(data.length, this.riskClusters[this.riskClusters.length - 1].topInterval + 1);
        let currentIndex = 0;
        for (var i = 0; i < this.riskClusters.length; i++) {
          for (var j = currentIndex; j < maxLimit; j++) {
            if (data[j].xValue <= this.riskClusters[i].topInterval) {
              result.push({
                score: data[j].xValue,
                primary: data[j].yValue,
                color: this.riskClusters[i].color,
              });
            }
            else {
              currentIndex = j;
              break;
            }
          }
        }

        let groupedData = UtilsService.aggregateDataByRiskCluster(this.riskClusters, data, 'universe');
        this.riskDistribution = groupedData;
      });
    });
  }

  public companiesLoaded(): void {
    this.gaService.hidePreloader();
  }

  public play(video: any): void {
    video.play();
  }

  public stop(video: any): void {
      video.pause();
      video.currentTime = 0;
  }
}
